<template>
    <div>
        <div id="videoDetail">
            <div class="videoDetail-video">
                <video-player class="video-player vjs-custom-skin"
                              ref="videoPlayer"
                              :playsinline="true"
                              :options="playerOptions">
                </video-player>
            </div>
            <!--<el-row class="userinfo">
                <el-col :span="1">
                    <el-avatar class="header-img" :size="50" :src="video.user.avatarUrl"></el-avatar>
                </el-col>
                <el-col :span="2">
                    <span class="video-userName">{{video.user.userName}}</span>
                </el-col>
            </el-row>-->
            <el-row><span class="video-title">{{video.title}}</span></el-row>
            <el-row>
                <time class="time video-createtime">{{ video.createTime|timestampToTime }}</time>
            </el-row>
            <el-row>
                {{video.viewsnum}}次播放
            </el-row>
            <el-row>
                <el-col :span="2">
                    <i v-if="isLike" @click="unlikevideo" style="color: #f3cd20" class="video-icon iconfont el-icon-dianzan1-copy-copy">    {{video.likenum}}</i>
                    <i v-else @click="likevideo" class="video-icon iconfont el-icon-dianzan1-copy">    {{video.likenum}}</i>
                </el-col>
                <el-col :span="2">
                    <i v-if="isCollect" @click="uncollectvideo" style="color: #f3cd20" class="video-icon iconfont el-icon-star1-copy-copy">    {{video.collectnum}}</i>
                    <i v-else @click="collectvideo" class="video-icon iconfont el-icon-star1-copy">    {{video.collectnum}}</i>
                </el-col>
            </el-row>
<!--            <el-row><span class="video-introduction">{{video.introduction}}</span></el-row>-->
            <el-row><TabBorder></TabBorder></el-row>
        </div>
        <div v-if="hasLogin" v-clickoutside="hideReplyBtn" @click="inputFocus" class="my-reply">
            <el-avatar class="header-img" :size="40" :src="userInfo.avatarUrl"></el-avatar>
            <div class="reply-info" >
                <div
                        tabindex="0"
                        contenteditable="true"
                        id="replyInput"
                        spellcheck="false"
                        placeholder="输入评论..."
                        class="reply-input"
                        @focus="showReplyBtn"
                        @input="onDivInput($event)"
                >
                </div>
            </div>
            <div class="reply-btn-box" v-show="btnShow">
                <el-button class="reply-btn" size="medium" @click="sendComment" type="primary">发表评论</el-button>
            </div>
        </div>
        <div v-for="(item,i) in comments" :key="i" class="author-title reply-father">
            <div>
                <el-avatar class="header-img" :size="40" :src="item.user.avatarUrl"></el-avatar>
                <div class="author-info">
                    <span class="author-name">{{item.user.userName}}</span>
                    <span class="author-time">{{item.createTime|timestampToTime}}</span>
                </div>
                <div v-if="hasLogin" class="icon-btn">
                <span @click="showReplyInput(i,item.user.userName,item.user.id,item.user.userCode)">
                    <i class="el-icon-chat-dot-square"></i>
                </span>
                    <span v-if="userInfo.id == item.user.id" @click="deleteComment(item.id)">
                    |
                    <i class="el-icon-delete"></i>
                </span>
                </div>
                <div class="talk-box">
                    <p>
                        <span class="reply">{{item.content}}</span>
                    </p>
                </div>
            </div>

            <div class="reply-box">
                <div v-for="(reply,j) in item.commentSecondList" :key="j" class="author-title">
                    <div>
                        <el-avatar class="header-img" :size="40" :src="reply.user.avatarUrl"></el-avatar>
                        <div class="author-info">
                            <span class="author-name">{{reply.user.userName}}</span>
                            <span class="author-time">{{reply.createTime|timestampToTime}}</span>
                        </div>
                        <div class="icon-btn" v-if="hasLogin">
                        <span @click="showReplyInput(i,reply.user.userName,reply.user.id,reply.user.userCode)">
                            <i class="el-icon-chat-dot-square"></i>
                        </span>
                            <span v-if="userInfo.id == reply.user.id" @click="deleteCommentReply(reply.id)">
                            |
                            <i class="el-icon-delete"></i>
                        </span>
                        </div>
                        <div class="talk-box">
                            <p>
                                <span>回复 {{reply.puser.userName}}：</span>
                                <span class="reply">{{reply.content}}</span>
                            </p>
                        </div>
                    </div>

                    <div class="reply-box">

                    </div>
                </div>
            </div>
            <div v-if="hasLogin" v-show="_inputShow(i)" class="my-reply my-comment-reply" @blur="onDivBlur($event)">
                <el-avatar class="header-img" :size="40" :src="userInfo.avatarUrl"></el-avatar>
                <div class="reply-info" >
                    <div tabindex="0" contenteditable="true" spellcheck="false" placeholder="输入评论..."  @input="onDivInput($event)" class="reply-input reply-comment-input"></div>
                </div>
                <div class=" reply-btn-box">
                    <el-button class="reply-btn" size="medium" @click="sendCommentReply(item.id,i)" type="primary">发表评论</el-button>
                </div>
            </div>
        </div>
        <div v-if="commentsLength == 0">
            <h3>暂时没有评论, 快来抢沙发吧(～￣▽￣)～</h3>
        </div>
    </div>
</template>

<script>
    import {selectVideoById} from "@/api/videoFun";
    import {getIsLike, insertLike, deleteLikeById} from "@/api/videoLikeFun";
    import {getIsCollect, insertCollect, deleteCollectById} from "@/api/videoCollectFun";
    import {insertCommentStair, insertCommentSecond, deleteCommentStair, deleteCommentSecond} from "@/api/commentFun";
    import TabBorder from "@/components/TabBorder";
    import {getStore, removeStore, delCookie} from "../../utils/util";
    import {Loading, Message, MessageBox} from 'element-ui';

    const clickoutside = {
        // 初始化指令
        bind(el, binding, vnode) {
            function documentHandler(e) {
                // 这里判断点击的元素是否是本身，是本身，则返回
                if (el.contains(e.target)) {
                    return false;
                }
                // 判断指令中是否绑定了函数
                if (binding.expression) {
                    // 如果绑定了函数 则调用那个函数，此处binding.value就是handleClose方法
                    binding.value(e);
                }
            }
            // 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听
            el.vueClickOutside = documentHandler;
            document.addEventListener('click', documentHandler);
        },
        update() {},
        unbind(el, binding) {
            // 解除事件监听
            document.removeEventListener('click', el.vueClickOutside);
            delete el.vueClickOutside;
        },
    };
    export default {
        name: "videoDetail",
        data(){
            return{
                video: {},
                playerOptions: {},

                userInfo: null,
                hasLogin: false,

                isLike: false,
                isCollect: false,

                btnShow: false,
                index:'0',
                replyComment:'',
                videoId : '',

                to:'',
                toId: '',
                toCode: '',

                commentsLength: 0,
                comments:[
                    {
                        userCode:'Lana Del Rey',
                        userId: 1,
                        userName: '',
                        id:'',
                        content:'',
                        createTime:'',
                        user:{
                            avatarUrl: "",
                            id: '',
                            userCode: "",
                            userName: "",
                        },
                        inputShow:false,
                        commentSecondList:[
                            {
                                puserCode:'',
                                puserId: '',
                                puserName: '',
                                userCode:'',
                                userId: '',
                                userName: '',
                                id:'',
                                content:'',
                                createTime:'',
                                inputShow:false,
                                puser:{
                                    avatarUrl: "",
                                    id: '',
                                    userCode: "",
                                    userName: "",
                                },
                                user:{
                                    avatarUrl: "",
                                    id: '',
                                    userCode: "",
                                    userName: "",
                                },
                            }
                        ]
                    }
                ]
            }
        },
        directives: {clickoutside},
        components:{
            TabBorder
        },
        created(){
            let userInfo = getStore("userInfo");
            if (userInfo) {
                this.userInfo = userInfo;
                this.hasLogin = true;
            }
        },
        mounted()
        {
            this.videoId = this.$route.query.videoId
            selectVideoById({
                id: this.videoId
            }).then(res=>{
                this.video = res.data;
                this.comments = res.data.commentStairList;
                this.commentsLength = res.data.commentStairList.length;
                console.log(this.commentsLength)
                this.playerOptions = {
                    playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
                    autoplay: false, // 如果为true,浏览器准备好时开始回放。
                    muted: false, // 默认情况下将会消除任何音频。
                    loop: false, // 是否视频一结束就重新开始。
                    preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
                    language: 'zh-CN',
                    aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
                    fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
                    sources: [{
                        type: "video/" + res.data.fileName.substring(res.data.fileName.lastIndexOf(".")+1),
                        src: res.data.fileUrl // url地址
                    }],
                    poster: res.data.thumb, // 封面地址
                    notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
                    controlBar: {
                        timeDivider: true, // 当前时间和持续时间的分隔符
                        durationDisplay: true, // 显示持续时间
                        remainingTimeDisplay: false, // 是否显示剩余时间功能
                        fullscreenToggle: true // 是否显示全屏按钮
                    }
                }
            })

            this.reload();

        },
        methods: {
            reload() {
                this.videoId = this.$route.query.videoId
                selectVideoById({
                    id: this.videoId
                }).then(res=> {
                    this.video = res.data;
                    this.comments = res.data.commentStairList;
                    this.commentsLength = res.data.commentStairList.length;
                });

                if (this.hasLogin == true) {
                    getIsLike({
                        videoId: this.videoId
                    }).then(res=>{
                        if (res.status == 200) {
                            this.isLike = res.data;
                        }else {
                            Message.error(res.message);
                        }
                    })

                    getIsCollect({
                        videoId: this.videoId
                    }).then(res=>{
                        if (res.status == 200) {
                            this.isCollect = res.data;
                        }else {
                            Message.error(res.message);
                        }
                    })
                }
            },
            inputFocus(){
                var replyInput = document.getElementById('replyInput');
                replyInput.style.padding= "8px 8px"
                replyInput.style.border ="2px solid blue"
                replyInput.focus()
            },
            showReplyBtn(){
                this.btnShow = true
            },
            hideReplyBtn(){
                this.btnShow = false
                replyInput.style.padding= "10px"
                replyInput.style.border ="none"
            },
            showReplyInput(i,userName,id,userCode){
                this.comments[this.index].inputShow = false
                this.index =i
                this.comments[i].inputShow = true
                this.to = userName
                this.toId = id
                this.toCode = userCode
            },
            _inputShow(i){
                return this.comments[i].inputShow
            },
            sendComment(){
                if(!this.replyComment){
                    this.$message({
                        showClose: true,
                        type:'warning',
                        message:'评论不能为空'
                    })
                }else{
                    if (this.replyComment.replace(" ","")=="") {
                        this.$message({
                            showClose: true,
                            type:'warning',
                            message:'评论不能为空'
                        })
                        return;
                    }
                    let a ={}
                    let input =  document.getElementById('replyInput')
                    a.content = this.replyComment;
                    a.videoId = this.videoId;

                    insertCommentStair(a).then(res=>{
                        if (res.status == 200){
                            this.reload();
                            this.replyComment = ''
                            input.innerHTML = '';
                            Message.success(res.message);
                        }else {
                            Message.error(res.message);
                        }
                    });


                }
            },
            sendCommentReply(pid,i){
                if(!this.replyComment){
                    this.$message({
                        showClose: true,
                        type:'warning',
                        message:'评论不能为空'
                    })
                }else{
                    if (this.replyComment.replace(" ","")=="") {
                        this.$message({
                            showClose: true,
                            type:'warning',
                            message:'评论不能为空'
                        })
                        return;
                    }
                    let a ={}
                    a.pid = pid;
                    a.puserCode = this.toCode;
                    a.puserId = this.toId;
                    a.puserName = this.to;
                    a.content = this.replyComment;

                    insertCommentSecond(a).then(res=>{
                        if (res.status == 200){
                            this.reload();
                            this.replyComment = ''
                            document.getElementsByClassName("reply-comment-input")[i].innerHTML = ""
                            Message.success(res.message);
                        }else {
                            Message.error(res.message);
                        }
                    });
                }
            },
            deleteComment(id) {
                MessageBox.confirm("是否删除该条评论？", '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleteCommentStair({
                        id: id
                    }).then(res=>{
                        if (res.status == 200){
                            Message.success(res.message);
                            this.reload();
                        }else {
                            Message.error(res.message);
                        }
                    })
                }).catch(() => {

                });
            },
            deleteCommentReply(id) {
                MessageBox.confirm("是否删除该条评论？", '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleteCommentSecond({
                        id: id
                    }).then(res=>{
                        if (res.status == 200){
                            Message.success(res.message);
                            this.reload();
                        }else {
                            Message.error(res.message);
                        }
                    })
                }).catch(() => {

                });
            },
            onDivInput: function(e) {
                this.replyComment = e.target.innerText;
            },
            dateStr(date){
                //获取js 时间戳
                var time=new Date().getTime();
                //去掉 js 时间戳后三位，与php 时间戳保持一致
                time=parseInt((time-date)/1000);
                //存储转换值
                var s;
                if(time<60*10){//十分钟内
                    return '刚刚';
                }else if((time<60*60)&&(time>=60*10)){
                    //超过十分钟少于1小时
                    s = Math.floor(time/60);
                    return  s+"分钟前";
                }else if((time<60*60*24)&&(time>=60*60)){
                    //超过1小时少于24小时
                    s = Math.floor(time/60/60);
                    return  s+"小时前";
                }else if((time<60*60*24*30)&&(time>=60*60*24)){
                    //超过1天少于30天内
                    s = Math.floor(time/60/60/24);
                    return s+"天前";
                }else{
                    //超过30天ddd
                    var date= new Date(parseInt(date));
                    return date.getFullYear()+"/"+(date.getMonth()+1)+"/"+date.getDate();
                }
            },
            likevideo(){
                if (this.hasLogin) {
                    insertLike({
                        videoId: this.videoId
                    }).then(res=>{
                        this.reload();
                    })
                }else {
                    this.$root.Bus.$emit('loginDialog', {
                        centerDialogVisible: true,
                        activeName: 'login'
                    })
                }
            },
            unlikevideo(){
                deleteLikeById({
                    videoId: this.videoId,
                    userId: this.userInfo.id
                }).then(res=>{
                    this.reload();
                })
            },
            collectvideo(){
                if (this.hasLogin) {
                    insertCollect({
                        videoId: this.videoId
                    }).then(res=>{
                        this.reload();
                    })
                }else {
                    this.$root.Bus.$emit('loginDialog', {
                        centerDialogVisible: true,
                        activeName: 'login'
                    })
                }
            },
            uncollectvideo(){
                deleteCollectById({
                    videoId: this.videoId,
                    userId: this.userInfo.id
                }).then(res=>{
                    this.reload();
                })
            }
        },
    }
</script>

<style lang="stylus" scoped>
    .my-reply
        padding 10px
        margin-bottom 20px
        /*background-color #fafbfc*/
        .header-img
            display inline-block
            vertical-align top
        .reply-info
            display inline-block
            margin-left 5px
            width 90%
            @media screen and (max-width:1200px) {
                width 80%
            }
            .reply-input
                min-height 20px
                line-height 22px
                padding 10px 10px
                color #ccc
                background-color #fff
                border-radius 5px
                &:empty:before
                    content attr(placeholder)
                &:focus:before
                    content none
                &:focus
                    padding 8px 8px
                    border 2px solid blue
                    box-shadow none
                    outline none
        .reply-btn-box
            height 25px
            margin 10px 0
            .reply-btn
                position relative
                float right
                margin-right 80px
    .my-comment-reply
        margin-left 50px
        .reply-input
            width flex
    .author-title:not(:last-child)
        border-bottom: 1px solid rgba(178,186,194,.3)
    .author-title
        padding 10px
        .header-img
            display inline-block
            vertical-align top
        .author-info
            display inline-block
            margin-left 5px
            width 60%
            height 40px
            line-height 20px
            >span
                display block
                cursor pointer
                overflow hidden
                white-space nowrap
                text-overflow ellipsis
            .author-name
                color #f3cd20
                font-size 18px
                font-weight bold
            .author-time
                font-size 14px
        .icon-btn
            width 15%
            padding 0 !important
            float right
            @media screen and (max-width : 1200px){
                width 20%
                padding 7px
            }
            >span
                cursor pointer
            .iconfont
                margin 0 5px
        .talk-box
            margin 0 50px
            >p
                margin 0
            .reply
                font-size 16px
                color #fff
        .reply-box
            margin 10px 0 0 50px
            /*background-color #efefef*/

    .videoDetail-video{
        margin: 30px 0px;
        color: white;
    }
    #videoDetail{
        font-family "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;
    }
    .userinfo{
        height: 50px;
        line-height: 50px;
    }
    .el-row{
        margin-bottom 20px;
    }
    .video-title{
        font-size 30px
    }
    .video-introduction{
        font-size 20px
    }
    .video-userName{
        font-size 20px;
    }
    .video-icon{
        font-size 20px;
    }

</style>
